package com.xywy.bloodandroid.act;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.NumberPicker.OnValueChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.xywy.bloodandroid.R;
import com.xywy.bloodandroid.base.BaseActivity;
import com.xywy.bloodandroid.bean.User;
import com.xywy.bloodandroid.util.Constants;
import com.xywy.bloodandroid.util.MD5;
import com.xywy.bloodandroid.vollery.OnVolleyResponseListener;
import com.xywy.bloodandroid.vollery.PostRequest;
import com.xywy.bloodandroid.vollery.VolleyManager;
import com.xywy.bloodandroid.widget.MyDialog;

/*
 * 个人资料
 */
@SuppressLint("NewApi")
public class MyInfoActivity extends BaseActivity {

	protected static final String TAG = "MyInfoActivity";
	private LinearLayout ll_name; // 姓名
	private LinearLayout ll_sex; // 性别
	private LinearLayout ll_height; // 身高
	private LinearLayout ll_weight; // 体重
	private LinearLayout ll_birthday; // 生日

	private TextView tv_name;
	private TextView tv_sex;
	private TextView tv_height;
	private TextView tv_weight;
	private TextView tv_birthday;

	private TextView middle_title;
	private RelativeLayout left_img;
	private String[] sex = { "男", "女" };
	private String[] weightArray;
	private String[] heightArray;

	@Override
	protected void initView(Bundle savedInstanceState) {
		setContentView(R.layout.act_info_mine);

		ll_name = (LinearLayout) findViewById(R.id.ll_name);
		ll_sex = (LinearLayout) findViewById(R.id.ll_sex);
		ll_height = (LinearLayout) findViewById(R.id.ll_height);
		ll_weight = (LinearLayout) findViewById(R.id.ll_weight);
		ll_birthday = (LinearLayout) findViewById(R.id.ll_birthday);

		tv_name = (TextView) findViewById(R.id.tv_name);
		tv_sex = (TextView) findViewById(R.id.tv_sex);
		tv_height = (TextView) findViewById(R.id.tv_height);
		tv_weight = (TextView) findViewById(R.id.tv_weight);
		tv_birthday = (TextView) findViewById(R.id.tv_birthday);

		middle_title = (TextView) findViewById(R.id.middle_title);
		middle_title.setText("个人资料");
		left_img = (RelativeLayout) findViewById(R.id.left_img);
	}

	@Override
	protected void initListener() {
		ll_name.setOnClickListener(this);
		ll_sex.setOnClickListener(this);
		ll_height.setOnClickListener(this);
		ll_weight.setOnClickListener(this);
		ll_birthday.setOnClickListener(this);
		left_img.setOnClickListener(this);
	}

	@Override
	protected void initData() {
		initValues();

	}

	@Override
	protected void onResume() {
		super.onResume();
		tv_name.setText(User.getInstance(this).getName());

	}

	/*
	 * 初始化数据
	 */
	private void initValues() {

		/* 展示之前保存的数据 */
		if ((User.getInstance(this).getBirthday() != null))
			tv_birthday.setText(User.getInstance(this).getBirthday());
		else
			tv_birthday.setText("请选择");
		if ((User.getInstance(this).getSex() != null))
			tv_sex.setText(User.getInstance(MyInfoActivity.this).getSex());
		else
			tv_sex.setText("请选择");

		if (User.getInstance(this).getHeight() != "") {
			tv_height.setText(User.getInstance(this).getHeight());

		} else {
			tv_height.setText("请选择");
		}

		if (User.getInstance(this).getWeight() != "") {
			tv_weight.setText(User.getInstance(this).getWeight());
		} else {
			tv_weight.setText("请选择");
		}

		/* 初始化体重和身高范围 */
		List<Integer> weightList = new ArrayList<Integer>(); // 体重
		for (int i = 2; i < 100; i++) {
			weightList.add(i);
		}
		weightArray = new String[weightList.size()];
		for (int i = 0; i < weightList.size(); i++) {
			weightArray[i] = weightList.get(i) + "";
		}
		weightList.clear();
		for (int i = 40; i < 200; i++) {
			weightList.add(i);
		}
		heightArray = new String[weightList.size()];
		for (int i = 0; i < weightList.size(); i++) {
			heightArray[i] = weightList.get(i) + "";
		}
		weightList.clear();
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.ll_name:
			Intent intent = new Intent(MyInfoActivity.this,
					ChangeNameActivity.class);

			intent.putExtra("user_name", tv_name.getText().toString());
			startActivity(intent);
			break;
		case R.id.ll_sex:
			showSexDialog();
			break;
		case R.id.ll_height:
			showHeightDialog();
			break;
		case R.id.ll_weight:
			showWeightDialog();
			break;
		case R.id.ll_birthday:
			showDatePickerDialog();
			break;
		case R.id.left_img:
			MyInfoActivity.this.finish();
			break;

		default:
			break;
		}
	}

	/* 性别 */
	@SuppressLint("NewApi")
	private void showSexDialog() {
		final MyDialog myDialog = new MyDialog(MyInfoActivity.this,
				R.style.MyDialogStyle);
		myDialog.show();
		myDialog.setCancelable(false);
		myDialog.setCanceledOnTouchOutside(false);
		myDialog.setContentView(R.layout.mydialog_twobutton_layout);
		TextView dialogTitle = (TextView) myDialog
				.findViewById(R.id.mydialog_title);
		dialogTitle.setText("设置性别");
		NumberPicker numberPicker = (NumberPicker) myDialog
				.findViewById(R.id.picker);
		// numberPicker.setFormatter(this);
		numberPicker.setOnValueChangedListener(new OnValueChangeListener() {

			@Override
			public void onValueChange(NumberPicker picker, int oldVal,
					int newVal) {
				tv_sex.setText(sex[newVal]);
				User.getInstance(MyInfoActivity.this).setSex(sex[newVal]);
			}
		});
		// numberPicker.setOnScrollListener(this);
		numberPicker.setDisplayedValues(sex);
		numberPicker.setMinValue(0);
		numberPicker.setMaxValue(sex.length - 1);
		if ("男".equals(tv_sex.getText().toString())) {
			numberPicker.setValue(0);
		} else if ("女".equals(tv_sex.getText().toString())) {
			numberPicker.setValue(1);
		}
		TextView leftButton = (TextView) myDialog
				.findViewById(R.id.mydialog_twobutton_layout_left_button);
		leftButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				myDialog.dismiss();
			}
		});
		leftButton.setVisibility(View.GONE);
		myDialog.findViewById(R.id.mydialog_twobutton_layout_right_button)
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						myDialog.dismiss();
						changOnServer();
					}
				});

	}

	// 体重选择
	private void showWeightDialog() {
		final MyDialog myDialog = new MyDialog(MyInfoActivity.this,
				R.style.MyDialogStyle);
		myDialog.show();
		myDialog.setContentView(R.layout.mydialog_twobutton_layout);
		TextView dialogTitle = (TextView) myDialog
				.findViewById(R.id.mydialog_title);
		dialogTitle.setText("选择体重");
		NumberPicker numberPicker = (NumberPicker) myDialog
				.findViewById(R.id.picker);
		numberPicker.setOnValueChangedListener(new OnValueChangeListener() {

			@Override
			public void onValueChange(NumberPicker picker, int oldVal,
					int newVal) {
				tv_weight.setText(weightArray[newVal] + "");
				User.getInstance(MyInfoActivity.this).setWeight(
						weightArray[newVal] + "");
			}
		});
		numberPicker.setDisplayedValues(weightArray);
		numberPicker.setMinValue(0);
		numberPicker.setMaxValue(weightArray.length - 1);
		/* 设置初始值 */
		if (User.getInstance(MyInfoActivity.this).getWeight() == "") {
			numberPicker.setValue(99 / 2+2);
			User.getInstance(context).setWeight(99 / 2 + "");
		} else {
			numberPicker.setValue(Integer.parseInt(User.getInstance(
					MyInfoActivity.this).getWeight()) - 2);
		}

		TextView leftButton = (TextView) myDialog
				.findViewById(R.id.mydialog_twobutton_layout_left_button);
		leftButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				tv_weight.setText(User.getInstance(MyInfoActivity.this)
						.getWeight());
				myDialog.dismiss();
			}
		});
		leftButton.setVisibility(View.GONE);
		myDialog.findViewById(R.id.mydialog_twobutton_layout_right_button)
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						myDialog.dismiss();
						tv_weight
								.setText(User.getInstance(context).getWeight());
						changOnServer();
					}
				});

	}

	// 身高选择
	private void showHeightDialog() {
		final MyDialog myDialog = new MyDialog(MyInfoActivity.this,
				R.style.MyDialogStyle);
		myDialog.show();
		myDialog.setContentView(R.layout.mydialog_twobutton_layout);
		TextView dialogTitle = (TextView) myDialog
				.findViewById(R.id.mydialog_title);
		dialogTitle.setText("选择身高");
		NumberPicker numberPicker = (NumberPicker) myDialog
				.findViewById(R.id.picker);
		numberPicker.setOnValueChangedListener(new OnValueChangeListener() {

			@Override
			public void onValueChange(NumberPicker picker, int oldVal,
					int newVal) {
				tv_height.setText(heightArray[newVal] + "");
				User.getInstance(MyInfoActivity.this).setHeight(
						heightArray[newVal] + "");

			}
		});
		numberPicker.setDisplayedValues(heightArray);
		numberPicker.setMinValue(0);
		numberPicker.setMaxValue(heightArray.length - 1);

		String lastValue = User.getInstance(this).getHeight();
		if (lastValue == "") {
			numberPicker.setValue(199 / 2);
			User.getInstance(context).setWeight("160");
		} else {
			numberPicker.setValue(Integer.parseInt(lastValue) - 40);
		}

		TextView leftButton = (TextView) myDialog
				.findViewById(R.id.mydialog_twobutton_layout_left_button);
		leftButton.setVisibility(View.GONE);
		leftButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				myDialog.dismiss();

			}
		});
		myDialog.findViewById(R.id.mydialog_twobutton_layout_right_button)
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						myDialog.dismiss();
						changOnServer();
					}
				});
	}

	/* 时间 */
	public void showDatePickerDialog() {
		System.out.println("showDatePickerDialog---");
		Calendar c = Calendar.getInstance();
		int mYear = c.get(Calendar.YEAR);
		int mMonth = c.get(Calendar.MONTH);
		int mDay = c.get(Calendar.DAY_OF_MONTH);

		String str = User.getInstance(this).getBirthday();
		if (!TextUtils.isEmpty(str)) {
			mYear = Integer.parseInt(str.substring(0, 4));
			mMonth = Integer.parseInt(str.substring(5, 7));
			mMonth = mMonth - 1;
			mDay = Integer
					.parseInt(str.substring(Math.max(str.length() - 2, 0)));

		}
		DatePickerDialog dialog = new DatePickerDialog(this, mDateSetListener,
				mYear, mMonth, mDay);
		dialog.show();

	}

	private OnDateSetListener mDateSetListener = new OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			monthOfYear = monthOfYear + 1;
			String birthday = "";
			if (monthOfYear < 10) {
				birthday = year + "-0" + monthOfYear + "-" + dayOfMonth;
				tv_birthday.setText(birthday);
			} else {
				birthday = year + "-" + monthOfYear + "-" + dayOfMonth;
				tv_birthday.setText(birthday);
			}
			User.getInstance(MyInfoActivity.this).setBirthday(birthday);
			changOnServer();
		}
	};

	/*
	 * 获取新的信息上传到服务器 <br> 修改主用户身高、性别、生日、昵称 参数： userid 用户中心id keyword edit(固定值)
	 * height 身高 sex 性别 birthday 生日 accountstr 昵称
	 */
	/*
	 * 修改姓名
	 */
	private void changOnServer() {
		String sign = null;
		try {
			sign = MD5.md5s(Constants.Sign + Constants.tag);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		String url = "http://api.wws.xywy.com/index.php?act=kbb&fun=resetProperty&tag="
				+ Constants.tag + "&sign=" + sign;
		PostRequest<String> postRequest = new PostRequest<String>(url,
				String.class, new OnVolleyResponseListener<String>() {

					@Override
					public void onError(VolleyError volleyError) {
						// showToast("修改失败！");
						Log.d(TAG, "修改失败！");
					}

					@Override
					public void onSuccess(String response) {
						try {
							JSONObject jsonObject = new JSONObject(response);
							int state = jsonObject.getInt("state");
							if (state == 200) {
								showToast("修改成功");
							} else {
								Log.d(TAG, "修改失败！");
								// showToast("修改失败！");
							}
						} catch (JSONException e) {
							// showToast("修改失败！");
							Log.d(TAG, "修改失败！");
							e.printStackTrace();
						}
					}
				});

		Map<String, String> params = new HashMap<String, String>();
		params.put("userid", User.getInstance(context).getUserid());
		params.put("app_id", "2");
		params.put("accountstr", User.getInstance(this).getAccountstr());
		int sex = 1;
		if (User.getInstance(this).getSex().equals("0")) { // 存在本地 0 男， 1女；
			sex = 1;
		} else { // 存在服务器 1男，2女
			sex = 2;
		}
		params.put("sex", sex + "");
		params.put("height", User.getInstance(this).getHeight());

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String time = User.getInstance(this).getBirthday();
		Date date = null;
		try {
			date = format.parse(time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if (date == null) { // 尚未储存当前的用户生日信息
			params.put("birthday", 0 + "");
		} else {
			params.put("birthday", date.getTime() / 1000 + "");
		}
		params.put("keyword", "edit");

		postRequest.setParams(params);
		postRequest.setIsParseJson(false);
		VolleyManager.addRequest(postRequest, "");

	}
}
